<?php

class ranglijstModule extends abstractModule
{
	public function indexAction()
	{
		return $this->twig->render('/ranglijst/index.twig',array());
	}

	public function ajaxAction()
	{
		$sql = "SELECT  r.id  FROM Race r
				ORDER BY r.createdat DESC LIMIT 0,1";
		$res = mysql_query($sql);
		while($ids = mysql_fetch_assoc($res))
			$id = $ids['id'];

		if(isset($id))
		{

			$sql = "SELECT  r.id rid, r.distance, s.id sid, s.*, l.*, l.id lid, l.distance ldistance  FROM Race r
					LEFT JOIN Koppel_Race_Skater krs ON r.id = krs.raceID
					LEFT JOIN Skater s ON s.id = krs.skaterID
					LEFT JOIN Lap l on (l.skaterID = s.id AND r.id = l.raceID)
					WHERE r.id = {$id}";
			$res = mysql_query($sql);
			$array = array();
			while($rs = mysql_fetch_assoc($res))
				$array[$rs['ldistance']][$rs['time']] = $rs;
				
			krsort($array);
			foreach($array as $key => &$val)
			{
				$keys[] = $key;
				ksort($val);
			}

			$sql = "SELECT * FROM skater_lines 
			ORDER BY `skater_lines`.`timestamp` DESC";
			$res = mysql_query($sql);
			$skaters=array();
			while($skater = mysql_fetch_assoc($res))
				if(!isset($skaters[$skater['skater_ID']]))
				{
					$skaters[$skater['skater_ID']] = $skater;
					$skatKeys[] = $skater['skater_ID'];
				}
		}
		if(isset($skatKeys))
		{
			$distance = $skaters[$skatKeys[sizeof($skatKeys)-1]]['distance'];
		}
		elseif(isset($keys[0])) 
		{
			$distance = $keys[0];
		}
		$ranglijst = array();
		if(isset($distance))
			$ranglijst = $array[$distance];

		return $this->twig->render('/ranglijst/ajax.twig',array('ranglijst'=>$ranglijst));
	}
}
?>